package com.mojo.quartz;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ScheduleExecutorService实现定时任务
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/10 17:16
 */
@Slf4j
public class ScheduleExecutorServiceDemo implements Runnable {
    private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(4, 8, 200L, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>() {
    });
    AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {

        //executor();
        //scheduleAtFixedRate();
        scheduleWithFixedDelay();
    }

    @SneakyThrows
    private static void scheduleWithFixedDelay() {
        //严格按照间隔时间执行任务,间隔时间以上一次任务执行完成后为起点
        executor.scheduleWithFixedDelay(new ScheduleExecutorServiceDemo(), 1, 1, TimeUnit.SECONDS);
        Thread.sleep(10000);
        executor.shutdown();
    }

    @SneakyThrows
    private static void scheduleAtFixedRate() {
        //保证时间段内的总执行次数，如果每次任务执行时间过长，后续的任务会加快执行速度
        executor.scheduleAtFixedRate(new ScheduleExecutorServiceDemo(), 1, 1, TimeUnit.SECONDS);
        Thread.sleep(10000);
        executor.shutdown();
    }


    private static void executor() {
        executor.execute(new ScheduleExecutorServiceDemo());

    }

    @Override
    @SneakyThrows
    public void run() {
        if (count.get() == 2) {
            Thread.sleep(3000);
        }
        count.getAndIncrement();
        log.info("{},>>>ScheduleExecutorServiceDemo>>>:{}", count.get(), Thread.currentThread().getName());
    }
}
